﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 建邦配料系统
{
    public partial class ChangePassword : Form
    {
        public ChangePassword()
        {
            InitializeComponent();
        }
        static String connetStr = "server=127.0.0.1;port=3306;user=root;password=952716; database=MySQL";
        //usr:用户名，password：数据库密码，database：数据库名
        MySqlConnection conn = new MySqlConnection(connetStr);
        private async void comboBox1_Click(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            await UsersAsync();
        }
        #region 读取用户表到GUI中
        public async Task UsersAsync()
        {
            using (MySqlConnection conn = new MySqlConnection(connetStr))
            {
                string sql1 = "select * from ingredientdb.loginmanagement";
                await conn.OpenAsync();
                MySqlCommand cmd1 = new MySqlCommand(sql1, conn);
                MySqlDataReader reader1 = cmd1.ExecuteReader();//执行ExecuteReader()返回一个MySqlDataReader对象
                while (reader1.Read())
                {
                    comboBox1.Items.Add(reader1.GetString("UserName"));

                }
            }
        }
        #endregion

        #region 修改密码
        public async Task ChangePasswordAsync()
        {
            using (MySqlConnection conn = new MySqlConnection(connetStr))
            {
                string sql1 = "UPDATE ingredientdb.loginmanagement SET Password='" + textBox2.Text + "' WHERE UserName='" + comboBox1.Text + "'";
                await conn.OpenAsync();
                MySqlCommand cmd1 = new MySqlCommand(sql1, conn);
                int n1 = cmd1.ExecuteNonQuery();  //使用命令返回数据
            }
        }
        #endregion
        private async void button1_Click(object sender, EventArgs e)
        {
            using (MySqlConnection conn = new MySqlConnection(connetStr))
            {
                string sql1 = "select * from ingredientdb.loginmanagement where UserName='" + comboBox1.Text + "';";
                //执行sql命令
                conn.Open();
                MySqlCommand cmd1 = new MySqlCommand(sql1, conn);
                MySqlDataReader reader1 = cmd1.ExecuteReader();//执行ExecuteReader()返回一个MySqlDataReader对象
                while (reader1.Read())
                {
                    if (textBox1.Text == reader1.GetString("Password"))
                    {
                        await ChangePasswordAsync();
                        MessageBox.Show("修改成功！");

                    }
                    else
                    {
                        MessageBox.Show("密码错误！");
                    }

                }
            }
        }
    }
}
